<template>
  <div>
    <data-wrapper
      :widgetModel="widgetData.model"
      :bookDir="widgetData.bookDir"
      :results="widgetData.results"
      :students="widgetData.students"
    ></data-wrapper>
  </div>
</template>

<script>
import { onMounted, reactive } from 'vue';
import DataWrapper from './components/DataWrapper';

const dataKeys = ['results', 'bookDir', 'model', 'students'];

export default {
  name: 'App',
  components: {
    DataWrapper
  },
  setup() {
    const widgetData = reactive({
      results: '[]',
      students: '[]',
      model: '{}',
      bookDir: ''
    });

    const handleMessage = (e) => {
      const { type, data } = e.data;
      if (type === 'renderData') {
        dataKeys.forEach((key) => {
          if (data[key] !== undefined) {
            // console.log(`[data received] key: ${key}`, data[key]);
            widgetData[key] = data[key];
          }
        });
      }
    };

    onMounted(() => {
      window.addEventListener('message', handleMessage);
      // 给父级窗口发消息当前应用已经创建成功。
      if (window.parent && window.parent !== window) {
        window.parent.postMessage({ type: 'statisticsViewer:created', data: 'pendulumTriangle' }, '*');
      } else if (window.opener) {
        window.opener.postMessage({ type: 'statisticsViewer:created', data: 'pendulumTriangle' }, '*');
      }
    });

    return {
      widgetData,
    }
  }
}
</script>

<style>
html, body {
  height: 100%;
  background-color: #fff;
  margin: 0;
}
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}
</style>
